<?php

/**
 * Get bibliographic data and item status from an Innovative Interfaces Catalog. 
 * Conforms to the DLF ILS Discovery Interface Task Group (ILS-DI) Technical 
 * Recommendation 1.1.
 * 
 * @author David Walker
 * @copyright 2009 The California State University
 * @link http://xerxes.calstate.edu
 * @version 0.1
 * @package Shrew
 * @license http://www.gnu.org/licenses/
 */

class Xerxes_Innopac extends Xerxes_Z3950
{
	private $http_server;
	
	public function __construct($server)
	{
		$match = explode(":", $server);
		$this->http_server = "http://" . $match[0];
		
		parent::__construct($server);
	}
	
	protected function parseHoldings(SimpleXMLElement $record)
	{
		$return = array();
		
		foreach ( $record->holdings->holding as $holding )
		{
			$item = new DLF_Item();
			$item->call_number = (string) $holding->callNumber;
			$item->location = (string) $holding->localLocation;
			$item->availabilitymsg = (string) $holding->publicNote;
			
			array_push($return, $item);
		}
		
		return $return;
	}

	public function doKeywordSearch($query, $start =1, $max = 10, $sort = "D")
	{
		$arrMatches = array();
		
		$query = strtolower( $query );
		$query = urlencode( $query );
		
		// build search phrase
		
		$strQuery =  "X" . $query;
		
		// get initial search results page
		
		$url =  $this->http_server . "/search/" . $strQuery;

		$response = file_get_contents( $url );
		
		if ( $this->total == 0  )
		{
			// extract the total number of hits in the results page;
	
			if ( preg_match( "/Entries<br \/> ([0-9]{1,10}) Found/", $response, $arrMatches ) != 0 )
			{
				$this->total = $arrMatches[1]; // browse search
			} 
			elseif ( preg_match( "/\(1-[0-9]{1,2} of ([0-9]{1,10})\)/", $response, $arrMatches ) != 0 )
			{
				$this->total = $arrMatches[1]; // keyword search
			} 
			elseif ( ! stristr( $response, "No matches found" ) && ! stristr( $response, "NO ENTRIES FOUND" ) )
			{
				$this->total =  1; // only found one response, catalog jumped right to full display 
			} 
			else
			{
				$this->total =  0;
			}
		}
		
		$numbers = $this->extractNumbers($response);
		
		return $numbers;
	}

	private function extractNumbers($html)
	{
		$pattern = "/=\"{0,1}(b[0-9]{7,10})/";
		$matches = array();
		$arrRecords = array();

		if ( preg_match_all($pattern, $html, $matches, PREG_SET_ORDER) )
		{
			foreach ( $matches as $match )
			{
				array_push($arrRecords, $match[1]);
			}
		}
		else
		{
			throw new Exception("Could not find records!");
		}
		
		return $arrRecords;
	}

}

?>
